﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestChemicalEquilibrium
{
    public delegate void OperateCallback();

    public class ThreadEventWait
    {
        public static AutoResetEvent EventWait = new AutoResetEvent(true);

        Thread Thread;

        OperateCallback Operate;

        int Timeout;

        public ThreadEventWait(int timeout, OperateCallback operate)
        {
            this.Timeout = timeout;

            this.Operate = operate;

            this.Thread = new Thread(new ThreadStart(ThreadFunction));
        }

        public void Start()
        {
            Thread.Start();
        }

        public void Abort()
        {
            Thread.Abort();
        }

        Random R = new Random();

        public void ThreadFunction()
        {
            while (true)
            {
                if (EventWait.WaitOne())
                {
                    EventWait.Reset();

                    this.Operate();

                    EventWait.Set();
                }

                Thread.Sleep(this.Timeout);
                //Thread.Sleep(R.Next(1000));
            }
        }
    }
}
